var app = getApp()
Page({
  data: {
    accessToken: "",
    isShow: false,
    results: [],
    src: "",
    isCamera: true,
    btnTxt: "拍照"
  },
  onLoad() {
    this.ctx = tt.createCameraContext()
    
    var token = tt.getStorageSync("TOKEN")
    if (token == undefined || token == "" || token == null) {
      app.GetBaiduAccessToken(function (res) {
        this.data.token = token
      })
    } else {
      this.data.token = token
    }
  },
  takePhoto() {
    var that = this
    if (this.data.isCamera == false) {
      this.setData({
        isCamera: true,
        btnTxt: "拍照"
      })
      return
    }
    this.ctx.takePhoto({
      quality: 'high',
      success: (res) => {
        this.setData({
          src: res.tempImagePath,
          isCamera: false,
          btnTxt: "重拍"
        })
        tt.showLoading({
          title: '正在加载中',
        })
        tt.getFileSystemManager().readFile({
          filePath: res.tempImagePath,
          encoding: "base64",
          success: res => {
            that.req(app.accessToken, res.data)
          },
          fail: res => {
            tt.hideLoading()
            tt.showToast({
              title: '拍照失败,未获取相机权限或其他原因',
              icon: "none"
            })
          }
        })
      }
    })
  },
  req: function (token, image) {
    var that = this
    app.func.req("https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general?access_token=" + token, {
      "image": image
    }, function (res) {
      tt.hideLoading()
      console.log(JSON.stringify(res))
      var num = res.result_num
      var results = res.data.result
      if (results != undefined && results != null) {
        that.setData({
          isShow: true,
          results: results
        })

        console.log(results)
      } else {
        tt.showToast({
          icon: 'none',
          title: 'AI识别失败,请联系管理员',
        })
      }
    }, "POST")
  },

  radioChange: function (e) {
    console.log(e)
    console.log(e.detail)
    console.log(e.detail.value)
    tt.navigateTo({
      url: '/pages/result/list?keyword=' + e.detail.value,
    })
  },
  hideModal: function () {
    this.setData({
      isShow: false,
    })
  },
  stopRecord() {
    this.ctx.stopRecord({
      success: (res) => {
        this.setData({
          src: res.tempThumbPath,
          videoSrc: res.tempVideoPath
        })
      }
    })
  },
  error(e) {
    console.log(e.detail)
  }

})